const https = require('https');// curl -k https://localhost:8000/
const SQLHelper =  require('./SQLHelper');
const { formatTime } = require('./util')
///雪花算法生成ID
const Snowflake = require('./snowflake')

const multer = require('multer')
// const upload = multer({ dest:'uploads/'})
const storage = multer.diskStorage({
    destination:'./uploads',
    ///获取uploads文件里面的图片
    filename: function (req, file, cb) {
        ///获取图片类型
        let fileType = file.originalname.split('.')    //从.裁剪内容
        fileType = fileType[fileType.length - 1]
        cb(null, Snowflake() + '.' + fileType)
        // console.log(file)
    }
})
const upload = multer({storage: storage })


module.exports = function(app){
//登录拦截中间件
function loginRouter(req,res,next){
    let token = req.headers.token
    // console.log(token)
    if(token){
        SQLHelper(`select * from session where id = ${token}`).then(ret => {
            if(ret.length){
                let session = ret[0]
                req.session = {
                    userId:session.userId,
                    userName:session.userName
                }
                next()
            }else{
                res.status(406).send({errorMsg:'当前用户未登录'})
            }
        })
    }else{
        res.status(405).send({errorMsg:'缺少token,请先进行登录'})
    }
}
///让初登录以外的所有小程序接口都要先验证登录
app.use('/wxapp',loginRouter)


///文件上传
app.post('/upload',upload.single('file'),(req,res) => {
    // console.log(req.file)
    res.send(req.file)
})

////微信登陆
app.get('/wxapplogin', (req, res,next) => {
    let code = req.query.code
    let appid = 'wx5ad3cbd204368fd1'
    let secret = '3a0dd4cad7886fce184122d9b32760f8'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {    
        ret.on('data', (ret) => {  
            ret = JSON.parse(ret.toString())   
            let openid = ret.openid     
            if(!openid){
                res.send({errorMsg: ret.errMsg || '获取openid错误'})
            }else{
                ///查询用户是否已经注册
                let queryMember = `select * from member where openId ='${openid}'`
                SQLHelper(queryMember).then(membersRet => {
                    if(membersRet.length){////用户已经存在
                        //挂载到req
                        req.member = membersRet[0]
                        next()
                    }else{///用户不存在，使用openid注册用户
                        SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
                            ///注册成功返回新用户信息
                            SQLHelper(queryMember).then(newMember => {
                                //挂载到req
                                req.member = membersRet[0]
                                next()
                            })
                        })
                    }
                })
            }
        });     
      }).on('error', (e) => {
            console.error(e);
            res.send({errorMsg:'获取openid错误'})
        }
    );
},(req,res) => {
    let member =  req.member
    let token = Snowflake()
    //缓存到tokens到session表
    SQLHelper(`
    INSERT INTO session(id,userId,userName,inTime,platform) 
    VALUES ('${token}','${member._id}','${member.nickName}','${formatTime(new Date())}','wxapp')
    `).then(ret => {
        res.send({
            nickName:member.nickName,
            token,
            openId:member.openId,
            avatarUrl:member.avatarUrl,
            _id:member._id
        })
    })
})

///修改用户信息
app.put('/wxapp/member',(req,res) => {
    let userInfo = req.body
    SQLHelper(`
    update member
    set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
    where _id = ${req.session.userId}
    `).then(ret => {
        // console.log(ret)    ////什么玩意
        res.send({})
    })
})


///get获取收获地址列表
///memberId 用户ID 必填
app.get('/wxapp/address',(req,res) => {
    if(req.session.userId){
        SQLHelper(`
        select * from address where state = 1 and memberId = ${req.session.userId}
        `).then(ret => {
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'请传入memberId'})
    }
})

///get获取category列表
///memberId 用户ID 必填
app.get('/wxapp/category',(req,res) => {
    if(!res.index_region){
        SQLHelper(`
        select * from index_region where state = 1 and type = 'category'
        `).then(ret => {
            // req.session = {
            //     userId:session.userId,
            //     userName:session.userName
            // }
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'出现错误请修改'})
    }
})

///最适合我自己的模板代码
///get获取美食列表recommend
///memberId 用户ID 必填
app.get('/wxapp/recommend',(req,res) => {
    if(!res.index_region){
        SQLHelper(`
        select * from index_region where status = 1 and type = 'recommend'
        `).then(ret => {
            // req.session = {
            //     userId:session.userId,
            //     userName:session.userName
            // }
            res.send(ret)
            // console.log(ret)
        })
    }else{
        res.send({errorMsg:'出现错误请修改'})
    }
})

//获取商家消息
app.get('/wxapp/userxj',(req,res) => {
    if(!res.userxj){
        SQLHelper(`
        select * from userxj where status = 1 
        `).then(ret => {
            // req.session = {
            //     userId:session.userId,
            //     userName:session.userName
            // }
            res.send(ret)
            // console.log(ret)
        })
    }else{
        res.send({errorMsg:'出现错误请修改'})
    }
})

///获取收获详情
///addressId 地址_id 必填
app.get('/wxapp/address/detail',(req,res) => {
    if(req.query.addressId){
        SQLHelper(`
        select * from address where _id = ${req.query.addressId}
        `).then(ret => {
            res.send(ret.length ? ret[0] : {errorMsg:'未获取地址详情'})
        })
    }else{
        res.send({errorMsg:'请传入addressId'})
    }
})

///post新增收货地址
///memberId 用户ID 必填
/// receiver 收货人 必填
/// phone 手机号 必填
/// city 省市区 必填
/// area 详情地址 非必填
app.post('/wxapp/address',(req,res) => {
    if(req.session.userId && req.body.receiver && req.body.phone && req.body.city){
        SQLHelper(`
        INSERT INTO address(state,memberId,receiver,phone,city,area) 
        VALUES (1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
        `).then(ret => {
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

///put修改收货地址
///address 地址_id 必填
/// receiver 收货人 非必填
/// phone 手机号 非必填
/// city 省市区 非必填
/// area 详情地址 非必填
app.put('/wxapp/address',(req,res) => {   
    if(req.body.addressId){
        //需要修改的项
        let updateKey = ['receiver','phone','city','area']
        let updateValues = []
        for(let i = 0;i < updateKey.length; i ++){
            let key = updateKey[i],value = req.body[key]
            if(value)  updateValues.push(`${key} = '${value}'`)  ///判断哪些需要修改
        }
        SQLHelper(`update address set ${updateValues.join(',')} where _id = ${req.body.addressId}`).then(ret => {
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

//修改为默认地址
///addressId 主码_id 必填
///memberId 用户_id 必填
///isDefault 是否必填 非必填
app.put('/wxapp/address/default',(req,res) => {
    let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault == 1 ? 1 : 0
    if(addressId && memberId){
        if(isDefault == 1){///设置为默认地址
            ///取消其他默认地址
            SQLHelper(`
            UPDATE address 
            set isDefault = 0
            WHERE isDefault = 1 AND memberId = ${memberId}
            `).then(ret => {
                SQLHelper(`
                UPDATE address 
                set isDefault = 1
                WHERE _id = ${addressId}
                `).then(ret => {
                    res.send(ret)
                })
            })
        }else{//取消默认地址
            SQLHelper(`
            UPDATE address 
            set isDefault = 0
            WHERE _id = ${addressId}
            `).then(ret => {
                res.send(ret)
            })
        }
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

//delete接口删除地址  逻辑删除
///addressId 主码_id 必填
app.delete('/wxapp/address',(req,res) => {
    let addressId = req.body.addressId
    if(addressId){       
                SQLHelper(`
                UPDATE address 
                set state = 0
                WHERE _id = ${addressId}
                `).then(ret => {
                    res.send(ret)
                })      
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

}
